package com.louzhu.gulimall.ware.service.impl;

import com.louzhu.common.constant.WareConstant;
import com.louzhu.gulimall.ware.entity.PurchaseDetailEntity;
import com.louzhu.gulimall.ware.service.PurchaseDetailService;
import com.louzhu.gulimall.ware.service.WareSkuService;
import com.louzhu.gulimall.ware.vo.MergeVo;
import com.louzhu.gulimall.ware.vo.PurchaseDoneVo;
import com.louzhu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.louzhu.common.utils.PageUtils;
import com.louzhu.common.utils.Query;

import com.louzhu.gulimall.ware.dao.PurchaseDao;
import com.louzhu.gulimall.ware.entity.PurchaseEntity;
import com.louzhu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        // 查询状态为 0 新建 或者 1 已分配的数据
        queryWrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),queryWrapper);
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {

        Long purchaseId = mergeVo.getPurchaseId();
        /*
            如果提交的采购单ID为空，表示没有选择要合并的采购单，就新建一个采购单
             */
        if(null == purchaseId){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            // 采购单状态 ： 新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            // 采购单创建日期
            purchaseEntity.setCreateTime(new Date());
            // 采购单修改日期
            purchaseEntity.setUpdateTime(new Date());
            // 新增采购单
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单状态是0,1才可以合并

        // 要合并的采购需求单ID列表
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 采购需求单ID
            detailEntity.setId(i);
            // 采购单ID
            detailEntity.setPurchaseId(finalPurchaseId);

            // 采购需求单状态： 已分配
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        // 批量更新采购需求单上的采购单信息
        purchaseDetailService.updateBatchById(collect);
        // 修改采购需求单的修改时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 先保证当前采购单是已分配或者新建状态才能领取
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            // 过滤null
            if (null != item) {
                // 过滤状态不是新建获取已分配
                Integer status = item.getStatus();
                if (status == WareConstant.PurchaseStatusEnum.CREATED.getCode() || status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                    return true;
                }
            }
            return false;
        }).map(item -> {
            // 状态更新为已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        // 修改采购单
        this.updateBatchById(purchaseEntityList);

        // 修改采购需求单状态
        purchaseEntityList.forEach((item)->{
            // 根据采购单ID获取关联的采购需求单列表
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(pde -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(pde.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            // 批量修改
            purchaseDetailService.updateBatchById(collect);
        });
    }

    /**
     * 采购完成
     * @param purchaseDoneVo
     */
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 采购单ID
        Long id = purchaseDoneVo.getId();

        // 改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> pde = new ArrayList<>();
        for (PurchaseItemDoneVo item:items){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                // 采购成功的入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
        }
    }

}